package com.whty.demo.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.whty.demo.pojo.Student;
import com.whty.demo.service.IStudentService;

@RestController
public class Demo {
	
	Logger logger = LoggerFactory.getLogger(Demo.class);
	
	@Autowired
	@Qualifier("studentServiceImpl")
	private IStudentService studentService;
	
	@RequestMapping("/demo/save")
	public String save(Student user){
		Student stu = new Student();
		if (StringUtils.isNotBlank(user.getName())) {
			stu.setName(user.getName());
		}
		if (StringUtils.isNotBlank(user.getAddress())) {
			stu.setAddress(user.getAddress());
		}
		if (user.getAge() != 0) {
			stu.setAge(user.getAge());
		}
		studentService.saveEntity(stu);
		String result = JSON.toJSONString(stu);
		return result;
	}
	
	@RequestMapping("/demo/update")
	public String update(Student user){
		Student stu = studentService.findOne(user.getId());
		if (!StringUtils.equalsIgnoreCase(user.getName(), stu.getName())) {
			stu.setName(user.getName());
		}
		if (!StringUtils.equalsIgnoreCase(user.getAddress(), stu.getAddress())) {
			stu.setAddress(user.getAddress());
		}
		if (user.getAge() != stu.getAge()) {
			stu.setAge(user.getAge());
		}
		logger.info("stu:"+JSON.toJSONString(stu));
		studentService.updateEntity(stu, user.getId());
		String result = JSON.toJSONString(stu);
		return result;
	}
	
	@RequestMapping("/demo/findOne")
	public String findOne(Student user){
		Student stu = studentService.findOne(user.getId());
		String result = JSON.toJSONString(stu);
		return result;
	}
	
	@RequestMapping("/demo/findAll")
	public String findAll(){
		List<Student> list = studentService.findAll();
		String result = JSON.toJSONString(list);
		return result;
	}

}
